//
//  UPLocationManager.m
//  Uang Pasti
//
//  Created by 李永彬 on 2025/8/17.
//

#import "UPLocationManager.h"

@interface UPLocationManager ()

@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, assign) BOOL isAlertViewShowing;
@property (nonatomic, strong) CLLocation *currentLocation;
@property (nonatomic, strong) CLPlacemark *currentPlacemark;
@property (nonatomic, copy) void (^completion)(UPLocationInfo info);
@property (nonatomic, strong) UPCustomAlertView *alertView;

@end

@implementation UPLocationManager

+ (instancetype)sharedManager {
    static UPLocationManager *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    }
    return self;
}

#pragma mark - Public Methods

- (void)upRequestLocationPermissionWithCompletion:(void (^)(BOOL))completion {
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
            [self.locationManager requestWhenInUseAuthorization];
            if (completion) completion(NO);
            break;
            
        case kCLAuthorizationStatusDenied:
        case kCLAuthorizationStatusRestricted:
            NSLog(@"定位权限被拒绝，引导用户去设置开启");
            [self upShowAlertView];
            if (completion) completion(NO);
            break;
            
        case kCLAuthorizationStatusAuthorizedWhenInUse:
        case kCLAuthorizationStatusAuthorizedAlways:
            [self upStartUpdatingLocation];
            if (completion) completion(YES);
            break;
            
        default:
            if (completion) completion(NO);
            break;
    }
}

- (void)upGetFullLocationInfoWithCompletion:(void (^)(UPLocationInfo))completion {
    self.completion = completion;
    
    __weak typeof(self) weakSelf = self;
    [self upRequestLocationPermissionWithCompletion:^(BOOL granted) {
        if (granted) {
            [weakSelf upStartUpdatingLocation];
        } else {
            if (completion) {
                UPLocationInfo emptyInfo = {0};
                completion(emptyInfo);
            }
        }
    }];
}

- (void)upGetCurrentWifiInfoWithCompletion:(void (^)(UPWifiInfo))completion {
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    
    if (@available(iOS 13.0, *)) {
        if (status == kCLAuthorizationStatusDenied) {
            NSLog(@"需要定位权限才能获取WiFi信息");
            [self upShowWifiPermissionAlert];
            if (completion) {
                UPWifiInfo emptyInfo = {0};
                completion(emptyInfo);
            }
            return;
        }
    }
    
    if (@available(iOS 14.0, *)) {
        [self upFetchWifiInfoWithNEHotspotNetworkWithCompletion:completion];
    } else {
        [self upFetchWifiInfoWithCNCopyWithCompletion:completion];
    }
}

#pragma mark - Private Methods

- (void)upStartUpdatingLocation {
    [self.locationManager startUpdatingLocation];
}

- (void)upShowAlertView {
    
    __weak typeof(self) weakSelf = self;
    if ([AppConfig sharedInstance].appCountryEnv != AppCountryEnvIndonesia) return;
    
    if (self.alertView && self.alertView.isAlertVisiable) {
        return;
    }

    UPCustomAlertView *alert = [[UPCustomAlertView alloc] initWithBackgroundImage:[UIImage imageNamed:@"alert_bg_image1"]
                                                                           style:UPAlertViewStyleCenter];
    [alert setTitle:@""
              font:[UIFont boldSystemFontOfSize:13]];

    [alert setContent:LocalizableForKey(@"LocationWhenInUseUsageDescription")
                font:[UIFont systemFontOfSize:13]];
    
    [alert addButtonWithTitle:LocalizableForKey(@"Open setting")
                        style:UPButtonStyleDefault
                      handler:^{
        upOpenAppSettings();
    }];

    [alert addButtonWithTitle:LocalizableForKey(@"Give up")
                        style:UPButtonStyleDestructive
                      handler:^{
    }];

    // 显示弹窗
    [alert showInView:[UIApplication up_currentKeyWindow]];
    self.alertView = alert;
}

- (void)upReverseGeocodeLocation:(CLLocation *)location {
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (error) {
            NSLog(@"反向地理编码失败: %@", error.localizedDescription);
            if (self.completion) {
                UPLocationInfo emptyInfo = {0};
                self.completion(emptyInfo);
            }
            return;
        }
        
        CLPlacemark *placemark = [placemarks firstObject];
        if (!placemark) {
            if (self.completion) {
                UPLocationInfo emptyInfo = {0};
                self.completion(emptyInfo);
            }
            return;
        }
        
        self.currentPlacemark = placemark;
        UPLocationInfo locationInfo = [self upCreateLocationInfoFromPlacemark:placemark location:location];
        if (self.completion) {
            self.completion(locationInfo);
        }
    }];
}

- (UPLocationInfo)upCreateLocationInfoFromPlacemark:(CLPlacemark *)placemark location:(CLLocation *)location {
    UPLocationInfo info;
    info.latitude = location.coordinate.latitude;
    info.longitude = location.coordinate.longitude;
    info.countryCode = placemark.ISOcountryCode;
    info.country = placemark.country;
    info.province = placemark.administrativeArea;
    info.city = placemark.locality ?: placemark.administrativeArea;
    info.district = placemark.subLocality;
    info.street = placemark.thoroughfare;
    info.formattedAddress = [self upFormatAddressFromPlacemark:placemark];
    return info;
}

- (NSString *)upFormatAddressFromPlacemark:(CLPlacemark *)placemark {
    NSMutableArray *addressComponents = [NSMutableArray array];
    
    if (placemark.thoroughfare) [addressComponents addObject:placemark.thoroughfare];
    if (placemark.subLocality) [addressComponents addObject:placemark.subLocality];
    if (placemark.locality) [addressComponents addObject:placemark.locality];
    if (placemark.administrativeArea) [addressComponents addObject:placemark.administrativeArea];
    if (placemark.country) [addressComponents addObject:placemark.country];
    
    return [addressComponents componentsJoinedByString:@", "];
}

#pragma mark - WiFi Methods

- (void)upFetchWifiInfoWithNEHotspotNetworkWithCompletion:(void (^)(UPWifiInfo))completion API_AVAILABLE(ios(14.0)) {
    [NEHotspotNetwork fetchCurrentWithCompletionHandler:^(NEHotspotNetwork * _Nullable currentNetwork) {
        if (!currentNetwork) {
            NSLog(@"NEHotspotNetwork获取失败");
            [self upFallbackToCNCopyWithCompletion:completion];
            return;
        }
        
        UPWifiInfo info;
        info.ssid = currentNetwork.SSID;
        info.bssid = currentNetwork.BSSID;
        info.signalStrength = 0;
        
        if (completion) completion(info);
    }];
}

- (void)upFetchWifiInfoWithCNCopyWithCompletion:(void (^)(UPWifiInfo))completion {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *ssid = nil;
        NSString *bssid = nil;
        
        NSArray *interfaces = (__bridge_transfer NSArray *)CNCopySupportedInterfaces();
        for (NSString *interface in interfaces) {
            NSDictionary *info = (__bridge_transfer NSDictionary *)CNCopyCurrentNetworkInfo((__bridge CFStringRef)interface);
            if (info) {
                ssid = info[(__bridge NSString *)kCNNetworkInfoKeySSID];
                bssid = info[(__bridge NSString *)kCNNetworkInfoKeyBSSID];
                break;
            }
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            UPWifiInfo info;
            info.ssid = ssid;
            info.bssid = bssid;
            info.signalStrength = 0;
            
            if (completion) completion(info);
        });
    });
}

- (void)upFallbackToCNCopyWithCompletion:(void (^)(UPWifiInfo))completion {
    if (@available(iOS 14.0, *)) {
        [self upFetchWifiInfoWithCNCopyWithCompletion:completion];
    } else {
        if (completion) {
            UPWifiInfo emptyInfo = {0};
            completion(emptyInfo);
        }
    }
}

- (void)upShowWifiPermissionAlert {
    // 实现与Swift版本相同的警告框逻辑
}

#pragma mark - CLLocationManagerDelegate

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    [self upRequestLocationPermissionWithCompletion:nil];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *location = [locations lastObject];
    if (!location) return;
    
    [manager stopUpdatingLocation];
    
    self.currentLocation = location;
    NSLog(@"当前位置：纬度 %f, 经度 %f", location.coordinate.latitude, location.coordinate.longitude);
    
    [UPUserDefaults setDouble:location.coordinate.latitude forKey:latitudeKey];
    [UPUserDefaults setDouble:location.coordinate.longitude forKey:longitudeKey];

    [self upReverseGeocodeLocation:location];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"定位失败：%@", error.localizedDescription);
    if (self.completion) {
        UPLocationInfo emptyInfo = {0};
        self.completion(emptyInfo);
    }
}

@end
